<template>
  <view class="container">
    <view class="address-form">
      <view class="form-item">
        <text class="label">收货人</text>
        <input 
          class="input" 
          placeholder="请输入收货人姓名" 
          v-model="addressForm.name"
        />
      </view>
      
      <view class="form-item">
        <text class="label">手机号码</text>
        <input 
          class="input" 
          placeholder="请输入手机号码" 
          v-model="addressForm.phone"
          type="number"
        />
      </view>
      
      <view class="form-item">
        <text class="label">所在地区</text>
        <view class="region-selector">
          <input 
            class="region-input" 
            placeholder="请选择省/市/区" 
            v-model="selectedRegion"
            @click="handleRegionInputClick"
          />
          <view class="map-icon" @click="goToMap">
            <uni-icons type="location-filled" size="16" color="#999"></uni-icons>
          </view>
        </view>
      </view>
      
      <view class="form-item">
        <text class="label">详细地址</text>
        <textarea 
          class="textarea" 
          placeholder="如道路、门牌号、小区、楼栋号、单元等"
          v-model="addressForm.detailAddress"/>
      </view>
      
    </view>
    <view class="form-item switch-item">
      <text class="label">设为默认地址</text>
      <switch 
        :checked="addressForm.isDefault" 
        @change="toggleDefault"
        color="#FF0000"
      />
    </view>
    <view class="form-buttons">
      <button class="save-btn" @click="saveAddress">保存</button>
    </view>
  </view>
</template>

<script>
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
import { addressApi } from '@/api/indexAPI.js';

export default {
  components: {
    uniIcons
  },
  data() {
    return {
      addressId: '',
      addressForm: {
        name: '',
        phone: '',
        province: '',
        city: '',
        region: '',
        detailAddress: '',
        isDefault: false
      },
      selectedRegion: ''
    };
  },
  onLoad(options) {
    // 获取传递的地址信息
    if (options.address) {
      this.initAddressData(options.address);
    }
  },
  methods: {
    initAddressData(addressData) {
      try {
        const address = typeof addressData === 'string' 
          ? JSON.parse(decodeURIComponent(addressData))
          : addressData;
        
        this.addressId = address.id || '';
        this.addressForm.name = address.name || '';
        this.addressForm.phone = address.tel || '';
        this.selectedRegion = address.address || '';
        this.addressForm.detailAddress = address.desc || '';
        
        // 关键优化：统一处理默认地址状态
        // 支持多种可能的字段名：default, isDefault, is_default
        const defaultStatus = address.default || address.isDefault || address.is_default;
        
        if (typeof defaultStatus === 'string') {
          this.addressForm.isDefault = defaultStatus === '1' || defaultStatus === 'true';
        } else if (typeof defaultStatus === 'number') {
          this.addressForm.isDefault = defaultStatus === 1;
        } else {
          this.addressForm.isDefault = !!defaultStatus;
        }
        
        console.log('初始化地址数据:', {
          原始数据: defaultStatus,
          转换后: this.addressForm.isDefault
        });
        
      } catch (error) {
        console.error('解析地址数据失败:', error);
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      }
    },
    
    handleRegionInputClick() {
      // 点击输入框时，允许用户手动输入
    },
    
    goToMap() {
      uni.navigateTo({
        url: '/pages/map/map'
      });
    },
    
    updateLocation(location) {
      this.selectedRegion = location.name;
      this.addressForm.province = location.address;
      this.addressForm.city = '';
      this.addressForm.region = '';
    },
    
    toggleDefault(e) {
      // 统一处理switch变化事件
      const isChecked = e.detail ? e.detail.value : e.target.value;
      this.addressForm.isDefault = isChecked;
      
      console.log('开关状态变化:', isChecked);
    },
    
    validateForm() {
      if (!this.addressForm.name) {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.addressForm.phone) {
        uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        });
        return false;
      }
      
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(this.addressForm.phone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.selectedRegion) {
        uni.showToast({
          title: '请选择所在地区',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.addressForm.detailAddress) {
        uni.showToast({
          title: '请输入详细地址',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },
    
    saveAddress() {
      if (!this.validateForm()) {
        return;
      }
      
      const userId = uni.getStorageSync('userId') || '';
      
      // 构造要提交的数据
      const requestData = {
        id: this.addressId,
        uid: userId,
        name: this.addressForm.name,
        tel: this.addressForm.phone,
        address: this.selectedRegion,
        desc: this.addressForm.detailAddress,
        default: this.addressForm.isDefault ? '1' : '0'
      };
      
      console.log('提交的数据:', requestData);
      
      addressApi.saveAddress(requestData).then(res => {
        if (res.code === 1) {
          uni.showToast({
            title: '编辑成功',
            icon: 'success'
          });
          
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        } else {
          uni.showToast({
            title: res.msg || '保存失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error("保存地址失败:", err);
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
      });
    }
  }
};
</script>

<style scoped>
/* 样式保持不变 */
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.address-form {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 0 30rpx;
}

.form-item {
  display: flex;
  align-items: center;
  min-height: 100rpx;
  border-bottom: 1rpx solid #eee;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  width: 180rpx;
  font-size: 28rpx;
  color: #333;
}

.input {
  flex: 1;
  font-size: 28rpx;
  padding: 20rpx 0;
}

.region-selector {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.region-input {
  flex: 1;
  font-size: 28rpx;
  padding: 0;
}

.map-icon {
  padding: 10rpx;
}

.textarea {
  flex: 1;
  height: 160rpx;
  padding: 20rpx 0;
  font-size: 28rpx;
}

.switch-item {
  width: 100%;
  height: 80rpx;
  margin-top: 20rpx;
  align-items: center;
  display: flex;
  background-color: white;
  padding: 20rpx;
  justify-content: space-between;
}

.form-buttons {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  padding: 20rpx 0 40rpx;
}

.save-btn {
  background-color: #FF0000;
  color: #fff;
  border: none;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
}
</style>